<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use App\Models\Cabinet;

use Swoole\Coroutine;
use Swoole\Timer;
use Swoole\Coroutine\Http\Client;
use Swoole\Coroutine\Channel;
use App\Handlers\WeconHandler;
use Swoole\Coroutine\MySQL;

class GetWeconDataEverySecend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get-wecon-data-every-secend';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command. 
     *
     * @return mixed
     */
    public function handle()
    {
        $postData['pageSize'] = 50;
        $postData['pageIndex'] = 1;
        Timer::tick(1000, function (int $timer_id) use ($postData) {
            $now = time();
            $cabinets = Redis::smembers(Cabinet::LOCAL_CABINET_LIST);
            $channel = new Channel(count($cabinets));
            $boxIds = Redis::smembers(Cabinet::WECON_BOX_LIST);
            foreach ($boxIds as $boxId) {
                $groups = Redis::smembers(Cabinet::WECON_GROUP_.$boxId);
                foreach ($groups as $oneGroup) {
                    $postData['boxId'] = $boxId;
                    $postData['groupId'] = $oneGroup;
                    \Swoole\Coroutine::create(function () use ($postData, $channel, $now) {
                        $oneInsertData['cabinet_id'] = Redis::get(Cabinet::WECON_GROUP_TO_LOCAL_CABINET_.$postData['groupId']);
                        $oneInsertData['created_time'] = $now;

                        $client = new Client('api.v-box.net', 80);
                        $param = WeconHandler::genPostParam($postData);
                        $client->setHeaders($param['header']);
                        $client->post('/box-data/api/we-data/realdata', $param['data']);
                        $oneRes = json_decode($client->body, true);

                        $d = [];
                        $isOnline = 0;
                        if ($oneRes && isset($oneRes['result']['list'])) {
                            foreach ($oneRes['result']['list'] as $onePoint) {
                                $key = 'a_'.$onePoint['monitorId'];
                                $d[$key] = floatval($onePoint['value']);
                                $isOnline = $onePoint['state'];
                            }
                            $oneInsertData['isOnline'] = $isOnline;
                            $oneInsertData['data'] = json_encode($d);
                        } else {
                            $oneInsertData['isOnline'] = 0;
                        }
                        $channel->push($oneInsertData);
                        $client->close();
                    });
                }
            }

            $insertSql = 'INSERT INTO `xfy_cabinet_data_test`(`cabinet_id`, `data`, `created_time`) VALUES ';
            $insertValue = '';

            for ($i=0; $i < count($cabinets); $i++) {
                $one = $channel->pop();
                if ($one) {
                    if ($one['isOnline']) {
                        $insertValue .= '('.$one['cabinet_id'].', \''.addslashes($one['data']).'\', '.$one['created_time'].'),';
                    }
                } else {
                    assert($channel->errCode === SWOOLE_CHANNEL_TIMEOUT);
                    break;
                }
            }
            if ($insertValue) {
                $sql = $insertSql.rtrim($insertValue, ',');
                $swooleMysql = new MySQL();
                $swooleMysql->connect([
                    'host'     => env('DB_HOST'),
                    'port'     => env('DB_PORT'),
                    'user'     => env('DB_USERNAME'),
                    'password' => env('DB_PASSWORD'),
                    'database' => env('DB_DATABASE'),
                ]);
                $res = $swooleMysql->query($sql);
                var_dump("kk = ".$res." = ".date('H:i:s'));
            }
        });
        \Swoole\Event::wait();

        return;
    }
}
